<?php

namespace app\company\controller\task\list;

use app\admin\service\GroupReportExportService;
use app\admin\service\TaskService;
use app\BaseController;
use app\company\service\PlatformService;
use app\model\not_del\DepartmentModel as NotDelDepartmentModel;
use app\model\not_del\UserModel as NotDelUserModel;
use app\model\platform\PlatformTaskContinuousEvaluationModel;
use app\model\platform\PlatformTaskModel;
use app\model\platform\PlatformTaskRatingScaleModel;
use app\model\platform\PlatformTaskUnitModel;
use app\model\TaskModel;
use app\model\TaskRatingScaleModel;
use app\model\UnitModel;
use think\App;

class TaskList extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new PlatformTaskModel();
    }

    /**
     * 任务列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['start_time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['start_time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['start_time', '<=', $param['end_time']];
                }
            }
            if (isset($param['status']) && strlen($param['status'])) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['unit_complete_rate'])) {
                $TaskService = new TaskService($this->app);
                $CompletionStatus = $TaskService->CompletionStatus($param['unit_complete_rate']);
                $where[] = ['unit_complete_rate', 'between', $CompletionStatus['value']];
            }
            if (!empty($param['is_month'])) {
                $where[] = ['time', 'between', [strtotime(date('Y-m-d')), strtotime(date('Y-m-t 23:59:59'))]];
            }
            $where[] = ['company_id','=',$this->userData['company_id']];
            $where[] = ['areas_id','=',$this->userData['areas_id']];
            $query = $this->mode->where($where);
            $data = $query->with([
                'user'
            ])->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$v) {
                $v['unit_complete_rate'] = $v['unit_complete_rate']*100;
                $v['role_name'] = match ($v['user_level']) {
                    1 => '省级平台管理员',
                    2 => '市级平台管理员',
                    3 => '区级平台管理员'
                };
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务量表
     * @return bool|string
     */
    public function RatingScale(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $PlatformTaskRatingScaleModel = new PlatformTaskRatingScaleModel();
            $data = $PlatformTaskRatingScaleModel->where('task_id', '=', $id)->with(['ratingScale'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务单位
     * @return bool|string
     */
    public function unit(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $data = $PlatformTaskUnitModel->where('task_id', '=', $id)
                ->with(['unit'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 终止任务
     * @return bool|string
     */
    public function end(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $info = $this->mode->find($id);
            $info->status = 3;
            $info->save();
            return success([], '终止成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除任务
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $info = $this->mode->find($id);
            $info->is_del = 1;
            $info->del_time = time();
            $info->save();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $PlatformTaskRatingScaleModel = new PlatformTaskRatingScaleModel();
            $PlatformTaskContinuousEvaluationModel = new PlatformTaskContinuousEvaluationModel();
            $info = $this->mode->with(['user'])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $TaskRatingScaleList = $PlatformTaskRatingScaleModel->where('task_id', '=', $id)
                ->with([
                    'ratingScale',
                ])->select()->toArray();
            $factorList = $PlatformTaskContinuousEvaluationModel->where('task_id', '=', $id)
                ->with([
                    'ContinuityRatingScale', 'RatingScaleFactor'
                ])->select()->toArray();
            $factorData = [];
            foreach ($factorList as $item) {
                $factorData[$item['rating_scale_id']][] = [
                    'factor_id' => $item['factor_id'],
                    'factor_name' => $item['factor_name'],
                    'rating_scale_id' => $item['continuity_rating_scale_id'],
                    'rating_scale_name' => $item['continuity_rating_scale_name'],
                ];
            }
            $rating_scale = [];
            foreach ($TaskRatingScaleList as $item) {
                $rating_scale[] = [
                    'id' => $item['rating_scale_id'],
                    'name' => $item['rating_scale_name'],
                    'factor' => $factorData[$item['rating_scale_id']] ?? []
                ];
            }
            //单位
            $unit_id = $PlatformTaskUnitModel->where('task_id', '=', $id)->distinct(true)->column('unit_id');
            $info['result_read_auth'] = explode(',', $info['result_read_auth']);
            $info['warning_rate'] = $info['warning_num'] > 0 ? round($info['warning_num']/$info['user_count'],2) : 0;
            $info['unit_complete_rate'] = $info['unit_complete_rate']*100;
            return success([
                'task' => $info,
                'uids' => $unit_id,
                'rating_scale' => $rating_scale,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑任务
     * @return false|string
     */
    public function update(): bool|string
    {
        $this->mode->startTrans();
        try {
            $taskData = $this->request->param('task');
            $this->validate($taskData, [
                'id|ID' => 'require|integer|max:11',
                'name|任务名称' =>  'require',
                'start_time|开始时间' =>  'require',
                'end_time|结束时间' =>  'require',
            ]);
            $info = $this->mode->find($taskData['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info->status != 1) throw new \Exception('未开始的任务才能编辑全部信息！');
            $info->is_del = 1;
            $info->del_time = time();
            $info->save();
            $PlatformTaskRatingScaleModel = new PlatformTaskRatingScaleModel();
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $PlatformContinuousEvaluationModel = new PlatformTaskContinuousEvaluationModel();
            $rating_scale = $this->request->param('rating_scale');
            $unit_id = $this->request->param('uids');
            if (empty($unit_id) || empty($rating_scale)) throw new \Exception('请选择量表和单位！');
            $rating_scale_column = array_column($rating_scale, 'id');
            if (count($rating_scale_column) !== count(array_unique($rating_scale_column))) throw new \Exception('量表不能重复选择！');
            $taskData['rating_scale_count'] = count($rating_scale);
            $taskData['unit_count'] = count($unit_id);
            $taskData['company_id'] = $this->userData['company_id'];
            $taskData['areas_id'] = $this->userData['areas_id'];
            $taskData['uid'] = $this->userData['id'];
            $taskData['time'] = $time = time();
            if ($taskData['start_time'] >= $time && $taskData['end_time'] <= $time) {
                //在任务时间内将任务设为进行中
                $taskData['status'] = 2;
            }
            if (!empty($taskData['result_read_auth'])) {
                $taskData['result_read_auth'] = implode(',', $taskData['result_read_auth']);
            }
            unset($taskData['id']);
            $task_id = $this->mode->insertGetId($taskData);
            //添加任务量表
            $task_rating_scale = [];
            $continuousData = [];
            foreach ($rating_scale as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    if ($item['id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                    $continuousData[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $time
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
                    'task_id' => $task_id,
                    'rating_scale_id' => $item['id'],
                    'time' => $time
                ];
            }
            //任务单位
            $task_unit = [];
            foreach ($unit_id as $v) {
                $task_unit[] = [
                    'task_id' => $task_id,
                    'unit_id' => $v,
                    'time' => $time
                ];
            }
            if (count($continuousData)) {
                $PlatformContinuousEvaluationModel->insertAll($continuousData);
            }
            if (count($task_rating_scale)) {
                $PlatformTaskRatingScaleModel->insertAll($task_rating_scale);
            }
            if (count($task_unit)) {
                $PlatformTaskUnitModel->insertAll($task_unit);
            }
            $this->mode->commit();
            return success([], '编辑成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑任务
     * @return false|string
     */
    public function update2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|任务ID' => 'require|integer|max:11',
                'unit_id|单位' => 'require',
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $old_unit_id = $PlatformTaskUnitModel->where('task_id','=',$param['id'])->column('unit_id');
            $task_unit = [];
            foreach ($param['unit_id'] as $v) {
                if (in_array($v, $old_unit_id)) continue;
                $task_unit[] = [
                    'task_id' => $param['id'],
                    'unit_id' => $v,
                    'time' => time()
                ];
            }
            if (count($task_unit)) {
                $PlatformTaskUnitModel->insertAll($task_unit);
            }
            $info->inc('unit_count',count($task_unit));
            $info->end_time = $param['end_time']??0;
            $info->save($param);
            return success([], '修改成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 任务详情-单位选择器
     * @return bool|string
     */
    public function UnitSelector(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $unit_id = $PlatformTaskUnitModel->where('task_id', '=', $id)->column('unit_id');
            $where = [];
            $where[] = ['id', 'in', $unit_id];
            $UnitModel = new UnitModel();
            $data = $UnitModel->field('id,level,province_id,city_id,area_id,province_name,city_name,area_name')
                ->where($where)->select()->toArray();
            if (empty($data)) return success();
            foreach ($data as &$item) {
                switch ($item['level']) {
                    case 1:
                        $item['num'] = $UnitModel->where([
                            ['id', 'in', $unit_id],
                            ['province_id', '=', $item['province_id']],
                        ])->count();
                        break;
                    case 2:
                        $item['num'] = $UnitModel->where([
                            ['id', 'in', $unit_id],
                            ['city_id', '=', $item['city_id']],
                        ])->count();
                        break;
                    case 3:
                        $item['num'] = $UnitModel->where([
                            ['id', 'in', $unit_id],
                            ['area_id', '=', $item['area_id']],
                        ])->count();
                        break;
                }
            }
            $PlatformService = new PlatformService($this->app);
            return success($PlatformService->leftOption($data));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务详情-单位联动器
     * @return bool|string
     */
    public function UnitLinkage(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer|max:11',
                'areas_id|ID' => 'require|integer|max:11',
                'pageSize|显示数量' => 'require|integer|max:11',
            ]);
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $TaskUnitList = $PlatformTaskUnitModel->with([
                'UnitTask'
            ])->where('task_id', '=', $param['id'])->select()->toArray();
            $unit_id = array_column($TaskUnitList, 'unit_id');
            $TaskUnitData = [];
            foreach ($TaskUnitList as $v) {
                $TaskUnitData[$v['unit_id']] = $v;
            }
            $where = [];
            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            $where[] = ['company_id','=',$this->userData['company_id']];
            $where[] = ['areas_id','=',$param['areas_id']];
            $where[] = ['id','in',$unit_id];
            $UnitModel = new UnitModel();
            $data = $UnitModel->field('id,name,banner,level,province_name,city_name,area_name')->where($where)->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
//                $item['unit_task_id'] = $TaskUnitData[$item['id']]['unit_task_id']??0;
                $item['is_finish'] = $TaskUnitData[$item['id']]['is_submit']??0;
                $item['unit_task_user_complete_rate'] = $TaskUnitData[$item['id']]['unit_task_user_complete_rate']??0;
                $item['unit_task_warning_num'] = $TaskUnitData[$item['id']]['unit_task_warning_num']??0;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 单位任务详情
     * @return bool|string
     */
    public function UnitTaskInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|任务ID' => 'require|integer|max:11',
                'unit_id|单位ID' => 'require|integer|max:11',
            ]);
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $info = $PlatformTaskUnitModel->where([
                ['task_id','=',$param['id']],
                ['unit_id','=',$param['unit_id']],
            ])->with([
                'SubmitUser' => function ($query) {
                    $query->with(['roleName']);
                },
                'UnitTaskInfo' => function ($query) {
                    $query->with([
                        'userNameRoleName' => function ($query) {
                            $query->with(['roleName']);
                        }
                    ]);
                },
                'unit'
            ])->find()->toArray();
            $info['submit_role_name'] = $info['submit_role_name']??'超级管理员';
            $info['UnitTaskInfo']['role_name'] = $info['UnitTaskInfo']['role_name']??'超级管理员';
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskRatingScaleList = $TaskRatingScaleModel->where('task_id', '=', $info['unit_task_id'])
                ->with([
                    'ratingScale'
                ])->select()->toArray();
            return success([
                'info' => $info,
                'TaskRatingScaleList' => $TaskRatingScaleList
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }



    /**
     * 任务测评团体报告
     * @return bool|string
     */
    public function TaskGroupReport(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $unit_id = $this->request->param('unit_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $unit_task_id = $PlatformTaskUnitModel->where([
                ['task_id', '=', $task_id],
                ['unit_id','in',$unit_id]
            ])->column('unit_task_id');
            $GroupReportExportService = new GroupReportExportService($this->app);
            return $GroupReportExportService->regionTaskGroupReportExportData($task_id, $unit_task_id, $rating_scale_id);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}